/** 实现这个项目的构建任务 */

// 文件模块
const fs = require('fs');
// 导入Gulp
const Gulp = require('gulp');
// 导入gulp-load-plugins自动注册插件
const plugins = require('gulp-load-plugins')();

const bs = require('browser-sync')
// swig模板插件
// const plugins.swig = require('gulp-swig');
//命令行解析工具
// const Minimist = require('minimist');
// const cmdOptions = Minimist(process.argv.splice(2));

// 编译Sass
// const Sass = require('gulp-sass');
// js转换
// const Babel = require('gulp-babel');
// 图片压缩
// const ImageMin = require('gulp-imagemin');

// 目标目录
const destPath = 'dist';
//  临时目录
const tempPath = 'temp';
// base目录，另外还有个public
const basePath = 'src';

const html = () => {
  const data = {
    menus: [
      {
        name: 'Home',
        link: 'index.html',
      },
      {
        name: 'About',
        link: 'about.html',
      }
    ],
    pkg: require('./package'),
    date: new Date()
  }
  return Gulp.src('src/*.html')
    .pipe(plugins.swig({data}))
    .pipe(Gulp.dest(tempPath))
    .pipe(bs.reload({stream: true}))
}
/**
 * 处理样式文件
 * @return {*}
 */
const style = () => {
  return Gulp.src('src/**/*.scss')
    .pipe(plugins.sass.sync({outputStyle: 'compressed'}).on('error', plugins.sass.logError))
    .pipe(Gulp.dest(tempPath))
    .pipe(bs.reload({stream: true}))
}
const js = () => {
  return Gulp.src('src/**/*.js')
    .pipe(plugins.babel({
      presets: ['@babel/env']
    }))
    .pipe(Gulp.dest(tempPath))
    .pipe(bs.reload({stream: true}))
}
const image = () => {
  return Gulp.src('src/assets/images/**', {base: basePath})
    .pipe(plugins.imagemin())
    .pipe(Gulp.dest(destPath))
}
const fonts = () => {
  return Gulp.src('src/assets/fonts/**', {base: basePath})
    .pipe(plugins.imagemin())
    .pipe(Gulp.dest(destPath))
}
const others = () => {
  return Gulp.src('public/**', {base: 'public'})
    .pipe(Gulp.dest(destPath))
}

/**
 * 删除上一次构建的文件夹及文件
 * @param callback
 */
const clean = (callback) => {
  /**
   * 删除文件夹及文件
   * @param path
   */
  function deleteFolder(path) {
    var files = [];
    if( fs.existsSync(path) ) {
      files = fs.readdirSync(path);
      files.forEach(function(file,index){
        var curPath = path + "/" + file;
        if(fs.statSync(curPath).isDirectory()) { // recurse
          // console.log('delete ======>'+curPath);
          deleteFolder(curPath);
        } else { // delete file
          fs.unlinkSync(curPath);
        }
      });
      fs.rmdirSync(path);
    }
  }
  deleteFolder(tempPath);
  deleteFolder(destPath);
  return callback();
}

/**
 * 服务器
 */
const serve = () => {
  Gulp.watch('src/**/*.js', js);
  Gulp.watch('src/**/*.scss', style);
  Gulp.watch('src/*.html', html);
  Gulp.watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**',
  ], bs.reload)
  bs.init({
    notify: false,
    port: 8888,
    open: false,
    // files: 'dist/**',
    server: {
      // 找不到文件时按顺序到各个目录下找
      baseDir: [tempPath, 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

/**
 * 解决html中直接引用node_modules文件问题，
 * @return {*}
 */
const useref = () => {
  return Gulp.src('temp/*.html', {base: tempPath})
    .pipe(plugins.useref({searchPath: [tempPath, '.']}))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.csso()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      removeComments: true,  //清除HTML注释
      collapseWhitespace: true,  //压缩HTML
      collapseBooleanAttributes: true,  //省略布尔属性的值 <input checked="true"/> ==> <input checked />
      removeEmptyAttributes: true,  //删除所有空格作属性值 <input id="" /> ==> <input />
      removeScriptTypeAttributes: true,  //删除<script>的type="text/javascript"
      removeStyleLinkTypeAttributes: true,  //删除<style>和<link>的type="text/css"
      minifyJS: true,  //压缩页面JS
      minifyCSS: true  //压缩页面CSS
    })))
    .pipe(Gulp.dest(destPath)); // 写到新的目录下，防止同一个目录的同时读写造成问题
}
// exports.html = html;
// exports.style = style;
// exports.js = js;
// exports.image = image;
// exports.fonts = fonts;
// exports.others = others;
// exports.clean = clean;
// exports.serve = serve;
// exports.useref = useref;
const compile = Gulp.parallel(html, style, js, image, fonts, others);
const develop = Gulp.series(compile, serve);

exports.clean = clean;
exports.develop = develop;
exports.compile = compile;
exports.build = Gulp.series(clean, Gulp.parallel(Gulp.series(compile, useref), image, fonts, others));
